package tasks

import (
	"log/slog"
	"os"
	"os/exec"

	"github.com/playwright-community/playwright-go"

	"torler.com/qingyue/pkg/env"
)

var browser playwright.Browser

func init() {
}

func InitBrowser(log *slog.Logger) {
	pw, err := playwright.Run()
	if err != nil {
		log.Error("could not start playwright: %v", err)
		return
	}

	// 查找系统已安装的 Chrome
	chromePath := findChromeExecutable()

	var launchOptions playwright.BrowserTypeLaunchOptions
	if env.IsDev() {
		// 开发模式：启动带UI的浏览器，便于调试
		launchOptions = playwright.BrowserTypeLaunchOptions{
			Headless: playwright.Bool(true),  // 显示浏览器窗口
			SlowMo:   playwright.Float(1000), // 减慢操作速度，便于观察
		}
		log.Info("Launched local browser in headed mode for development")
	} else {
		// 生产模式：无头模式运行
		launchOptions = playwright.BrowserTypeLaunchOptions{
			Headless: playwright.Bool(true),
			Args: []string{
				"--no-sandbox",
				"--disable-dev-shm-usage",
				"--disable-gpu",
			},
		}
		log.Info("Launched local browser in headless mode")
	}

	// 如果找到了系统安装的 Chrome，则使用它
	if chromePath != "" {
		log.Info("Using system Chrome executable: %s", chromePath)
		launchOptions.ExecutablePath = playwright.String(chromePath)
	} else {
		log.Info("Using Playwright's bundled browser")
	}

	bw, err := pw.Chromium.Launch(launchOptions)
	if err != nil {
		log.Error("could not launch browser: %v", err)
		return
	}
	browser = bw
}

func findChromeExecutable() string {
	// 常见的 Chrome/Chromium 可执行文件路径
	paths := []string{
		// Linux
		"/usr/bin/google-chrome",
		"/usr/bin/chromium-browser",
		"/usr/bin/chromium",
		"/usr/local/bin/google-chrome",
		"/usr/local/bin/chromium-browser",
		"/usr/local/bin/chromium",

		// Windows
		"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
		"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",

		// macOS
		"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
		"/Applications/Chromium.app/Contents/MacOS/Chromium",
	}

	// 检查环境变量中是否指定了 Chrome 路径
	if customPath := os.Getenv("CHROME_EXECUTABLE"); customPath != "" {
		if _, err := os.Stat(customPath); err == nil {
			return customPath
		}
	}

	// 查找系统中的 Chrome 可执行文件
	for _, path := range paths {
		if _, err := os.Stat(path); err == nil {
			return path
		}
	}

	// 尝试使用 which/where 命令查找
	if path, err := exec.LookPath("google-chrome"); err == nil {
		return path
	}
	if path, err := exec.LookPath("chromium-browser"); err == nil {
		return path
	}
	if path, err := exec.LookPath("chromium"); err == nil {
		return path
	}

	return ""
}
